package com.aat.dxfy.protostuff;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

public class Test {

	public static void main(String[] args) {
		PerformanceReport report = new PerformanceReport("Able", 26);
		byte[] bs = serializeProtoStuffReport(report);
		for (byte b : bs) {
			char c=(char) b;
			System.out.println(b+","+new Character(c));
		}
		System.out.println(new String(bs));
		PerformanceReport tmp = deserializeProtoStuffReport(bs);
		System.out.println(tmp);
	}

	// 1,
	public static byte[] serializeProtoStuffReport(PerformanceReport report) {
		Schema<PerformanceReport> schema = RuntimeSchema.getSchema(PerformanceReport.class);
		LinkedBuffer buffer = LinkedBuffer.allocate(4096);
		byte[] protostuff = null;
		try {
			protostuff = ProtostuffIOUtil.toByteArray(report, schema, buffer);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			buffer.clear();
		}
		return protostuff;
	}

	// 2,
	public static void byteToFile(byte[] bytes, String filepath) {

		FileOutputStream fos = null;

		File out = new File(filepath);

		if (out.exists()) {
			out.delete();
		}

		try {
			out.createNewFile();
			fos = new FileOutputStream(filepath);
			fos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();

		} finally {

			if (fos != null) {

				try {

					fos.close();

				} catch (IOException e) {

					e.printStackTrace();

				}

			}

		}

	}

	// 3,
	public static byte[] fileToBytes(String filepath) {
		Path path = Paths.get(filepath);
		byte[] data = null;
		try {
			data = Files.readAllBytes(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	// 4,
	public static PerformanceReport deserializeProtoStuffReport(byte[] bs) {

		Schema<PerformanceReport> schema = RuntimeSchema.getSchema(PerformanceReport.class);

		PerformanceReport product = new PerformanceReport();

		ProtostuffIOUtil.mergeFrom(bs, product, schema);

		return product;

	}

}

class PerformanceReport implements Serializable {
	private static final long serialVersionUID = 1L;
	private String name;
	private int age;

	public PerformanceReport() {
		super();
	}

	public PerformanceReport(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "PerformanceReport [name=" + name + ", age=" + age + "]";
	}

}